package org.hcf.api.base;

import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Random;

@Slf4j
public class CaptchaGenerator {
    public static int len = 4;
    public static int defaultHeight = 30;

    public static void main(String[] args) throws IOException {
        String text = generateRandomString(len); // 生成4位随机数字验证码
        BufferedImage image = createImage(text); // 创建图片
        drawImage(image, text); // 绘制图片
        writeImage(image, "captcha.png"); // 保存图片到文件
    }

    public static byte[] getRandomImage(String text) {
//        String text = generateRandomString(len); // 生成4位随机数字验证码
        BufferedImage image = createImage(text); // 创建图片
        drawImage(image, text); // 绘制图片
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "png", out);
            return out.toByteArray();
        } catch (Throwable ex) {
        }
        return null;
    }

    public static String generateRandomString(int length) {
        Random random = new Random();
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            sb.append(random.nextInt(10)); // 生成0-9的随机数字
        }
        log.info("生成验证码:" + sb.toString());
        return sb.toString();
    }

    private static BufferedImage createImage(String text) {
        int height = defaultHeight, width = height * len / 2;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);
        g.setColor(Color.BLUE);
        g.drawRect(0, 0, width - 1, height - 1);
        g.setColor(Color.BLACK);
        g.setFont(new Font("Arial", Font.BOLD, 20));
        g.drawString(text, 10, 25);
        g.dispose();
        return image;
    }

    private static void drawImage(BufferedImage image, String text) {
        int height = defaultHeight, width = height * len / 2;
        Graphics2D g = (Graphics2D) image.getGraphics();
        for (int i = 0; i < 5; i++) { // 绘制5条干扰线
            int x1 = new Random().nextInt(width);
            int y1 = new Random().nextInt(height);
            int x2 = new Random().nextInt(width);
            int y2 = new Random().nextInt(height);
            g.setColor(Color.GRAY);
            g.drawLine(x1, y1, x2, y2);
        }
        // 将验证码文本的字符随机颜色显示
        for (int i = 0; i < text.length(); i++) {
            g.setColor(new Color(new Random().nextInt(255), new Random().nextInt(255), new Random().nextInt(255)));
            g.drawString(text.charAt(i) + "", i * 20 + 5, 25);
        }
    }

    private static void writeImage(BufferedImage image, String path) throws IOException {
        ImageIO.write(image, "png", new File(path));
    }
}